<template>
  <!--  查询框区-->
  <div class="search">
    <el-form inline :model="memberSearchModel" ref="memberSearchForm">
      <el-form-item label="会员姓名: ">
        <el-input v-model="memberSearchModel.name" placeholder="请输入会员姓名" clearable/>
      </el-form-item>
      <el-form-item label="手机号: ">
        <el-input v-model="memberSearchModel.phone" placeholder="请输入手机号" clearable/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="Search" @click="search()">查询</el-button>
        <el-button :icon="Refresh" @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
  </div>

  <!--  按钮区 -->
  <div class="action">
    <el-button type="primary" :icon="CirclePlus" @click="add">新增</el-button>
    <el-button type="primary" :icon="Edit" @click="edit">修改</el-button>
    <el-button type="primary" :icon="Search" @click="search()">查询</el-button>
    <el-button type="primary" :icon="Refresh" @click="reset">重置</el-button>
    <el-button type="danger" :icon="Delete" @click="remove() ">退会</el-button>
  </div>

  <!--  表格区-->
  <div class="grid">
    <el-table :data="members"
              stripe
              border
              @row-click="tblRowClick"
              ref="tblRef"
              style="width: 100%">
      <el-table-column type="selection" align="center" width="60"/>
      <el-table-column prop="id" label="编号" align="center" width="100"/>
      <el-table-column prop="name" label="姓名" align="center" min-width="150"/>
      <el-table-column prop="phone" label="手机号" min-width="180" align="center"/>
      <el-table-column label="创建时间" min-width="180" align="center">
        <template #default="scope">
          {{ formatDateTime(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="vip" label="会员" align="center" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.vip === 0 ? 'success' : 'danger'">
            {{ scope.row.vip === 0 ? '已入会' : '未入会' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="240" align="center" fixed="right">
        <template #default="scope">
          <el-button type="primary" size="small" @click.stop="showCourse(scope.row)">课程</el-button>
          <el-button type="primary" size="small" @click.stop="editRow(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click.stop="deleteRow(scope.row)">退会</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>

  <!--  添加、修改弹出表单-->
  <el-dialog :title="memberDlgTitle" v-model="memberDlgShow" draggable align-center :close-on-click-modal="false"
             @close="resetMemberForm">
    <el-form label-width="100" label-position="right" :model="memberModel" ref="memberFormRef" :rules="memberRules">
      <el-row>
        <el-col :span="24">
          <el-form-item prop="name" label="姓名：">
            <el-input v-model="memberModel.name" placeholder="请输入会员姓名"/>
          </el-form-item>
          <el-form-item prop="phone" label="手机号：">
            <el-input v-model="memberModel.phone" placeholder="请输入手机号"/>
          </el-form-item>
          <el-form-item prop="password" label="密码：" v-if="mode === 'add'">
            <el-input v-model="memberModel.password" placeholder="请输入密码" type="password"/>
          </el-form-item>
          <el-form-item prop="vip" label="会员：">
            <el-radio-group v-model="memberModel.vip">
              <el-radio :label="1">未入会</el-radio>
              <el-radio :label="0">已入会</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div>
        <el-button @click="memberDlgShow=false">取消</el-button>
        <el-button type="primary" @click="submit" :loading="dialogLoading">确定</el-button>
      </div>
    </template>
  </el-dialog>

  <el-dialog title="预约课程" v-model="courseDlgShow" draggable align-center :close-on-click-modal="false" width="70%">
    <div class="course-info">
      <!-- 添加状态筛选下拉框 -->
      <div class="status-filter" style="margin-bottom: 15px; display: flex; align-items: center;">
        <span style="margin-right: 15px;">状态筛选:</span>
        <el-select v-model="courseStatusFilter" placeholder="请选择预约状态" clearable @change="filterByStatus" style="width: 200px;">
          <el-option label="全部状态" value=""></el-option>
          <el-option label="已预约" value="1"></el-option>
          <el-option label="已取消" value="2"></el-option>
          <el-option label="已完成" value="3"></el-option>
        </el-select>
      </div>
      <el-table :data="courseList" stripe border style="width: 100%">
        <el-table-column type="index" label="序号" width="60" align="center"/>
        <el-table-column prop="courseName" label="课程名称" align="center"/>
        <el-table-column prop="coachName" label="教练" align="center"/>
        <el-table-column prop="classTime" label="上课时间" align="center">
          <template #default="scope">
            {{ formatDateTime(scope.row.classTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="room" label="教室" align="center"/>
        <el-table-column prop="status" label="状态" align="center">
          <template #default="scope">
            <el-tag :type="getCourseStatusLabel(scope.row.status).type">
              {{ getCourseStatusLabel(scope.row.status).text }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="reserveTime" label="预约时间" align="center">
          <template #default="scope">
            {{ formatDateTime(scope.row.reserveTime) }}
          </template>
        </el-table-column>
      </el-table>

      <div class="dialog-footer" style="margin-top: 20px; text-align: right">
        <el-button @click="courseDlgShow = false">关闭</el-button>
      </div>
    </div>
  </el-dialog>


  <!--  分页区-->
  <div class="pagination">
    <el-pagination
        v-model:current-page="membersPi.pageNo"
        v-model:page-size="membersPi.pageSize"
        layout="prev, pager, next"
        :total="membersPi.total"
        @current-change="memberPiChange"
    />
  </div>
</template>

<script setup>
  import {onMounted, reactive, ref, toRaw, nextTick} from "vue"
import api from "@/utils/api.js";
import {CirclePlus, Delete, Edit, Refresh, Search} from "@element-plus/icons-vue";
import {ElMessage, ElMessageBox} from "element-plus";
import {cloneDeep} from "lodash";

// 表格数据
let members = ref([])
let dialogLoading = ref(false)

// 查询表单引用
let memberSearchForm = ref()
// 表格引用
let tblRef = ref()

// 分页
let membersPi = reactive({
  pageNo: 1,
  pageSize: 7,
  total: 0
})

// 查询条件
let memberSearchModel = ref({
  name: "",
  phone: ""
})

// 会员表单验证规则
const memberRules = {
  name: [
    {required: true, message: '请输入会员姓名', trigger: 'blur'},
    {min: 2, max: 20, message: '姓名长度应在 2 到 20 个字符之间', trigger: 'blur'}
  ],
  phone: [
    {required: true, message: '请输入手机号', trigger: 'blur'},
    {pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur'}
  ],
  password: [
    {required: true, message: '请输入密码', trigger: 'blur'},
    {min: 6, max: 20, message: '密码长度应在 6 到 20 个字符之间', trigger: 'blur'}
  ]
}

// 格式化日期时间
function formatDateTime(dateTimeString) {
  if (!dateTimeString) return ''
  const date = new Date(dateTimeString)
  return date.toLocaleString()
}

// 查询会员
async function search(pageNo = 1, pageSize = 7, params) {
  params = memberSearchModel.value
  try {
    let resp = await api({
      url: "/member",
      method: "get",
      params: {
        pageNo,
        pageSize,
        ...params
      }
    });
    if (resp.success) {
      members.value = resp.data.records
      membersPi.total = resp.data.total
      membersPi.pageNo = resp.data.current
      membersPi.pageSize = resp.data.size
    }
  } catch (error) {
    ElMessage.error("查询失败: " + (error.message || "网络错误"))
  }
}

// 重置查询条件
function reset() {
  memberSearchModel.value = {
    name: "",
    phone: ""
  }
  search()
}

// 表格行点击
function tblRowClick(row) {
  tblRef.value.toggleRowSelection(row)
}

// 删除会员
async function deleteMemberById(ids) {
  try {
    let resp = await api({
      url: "/member/changeVip",
      method: "put",
      data: ids
    })
    if (resp.success) {
      ElMessage.success("删除成功")
      search(membersPi.pageNo, membersPi.pageSize);
    } else {
      ElMessage.error("删除失败: " + (resp.message || "未知错误"))
    }
  } catch (error) {
    ElMessage.error("删除失败: " + (error.message || "网络错误"))
  }
}

function remove() {
  let rows = tblRef.value.getSelectionRows();
  if (rows.length === 0) {
    ElMessage.warning("请选择要退会的会员")
  } else {
    ElMessageBox.confirm(`确定要使选中的 ${rows.length} 个会员退会吗？`, "退会确认", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    }).then(() => {
      let ids = rows.map(item => item.id);
      deleteMemberById(ids);
    }).catch(() => {
      ElMessage.info("已取消退会")
    })
  }
}

// 弹窗相关
let memberDlgTitle = ref("新增会员")
let memberDlgShow = ref(false)
let mode = "add"

// 会员表单数据
let memberModel = ref({
  id: null,
  name: null,
  phone: null,
  password: null,
  create_time: null,
  vip: 1
})

let memberFormRef = ref();

function add() {
  mode = "add"
  memberDlgTitle.value = "新增会员"
  memberDlgShow.value = true
  // 重置表单
  nextTick(() => {
    memberModel.value = {
      id: null,
      name: null,
      phone: null,
      password: null,
      create_time: null
    }
  })
}

function edit() {
  let rows = tblRef.value.getSelectionRows();
  if (rows.length === 0) {
    ElMessage.warning("请选择要修改的行")
  } else if (rows.length > 1) {
    ElMessage.warning("只能选择一行")
  } else {
    mode = "edit"
    memberDlgTitle.value = "修改会员"
    memberDlgShow.value = true
    nextTick(() => {
      let row = rows[0]
      memberModel.value = {
        id: row.id,
        name: row.name,
        phone: row.phone,
        vip: row.vip
      }
    })
  }
}

function editRow(row) {
  mode = "edit"
  memberDlgTitle.value = "修改会员"
  memberDlgShow.value = true
  nextTick(() => {
    memberModel.value = {
      id: row.id,
      name: row.name,
      phone: row.phone,
      vip: row.vip
    }
  })
}

function resetMemberForm() {
  if (memberFormRef.value) {
    memberFormRef.value.resetFields()
  }
}

async function submit() {
  // 表单验证
  try {
    await memberFormRef.value.validate()
  } catch (error) {
    ElMessage.warning("请检查输入信息")
    return
  }

  dialogLoading.value = true

  let params = toRaw(memberModel.value)

  let url, method
  if (mode === 'add') {
    url = "/member"
    method = "post"
  } else if (mode === 'edit') {
    url = "/member"
    method = "put"
  }

  try {
    let resp = await api({
      url,
      method,
      data: params
    })
    if (resp.success) {
      ElMessage.success(mode === 'add' ? '添加成功' : '修改成功')
      memberDlgShow.value = false
      await search(membersPi.pageNo, membersPi.pageSize)
    } else {
      ElMessage.error(resp.message || '操作失败')
    }
  } catch (error) {
    ElMessage.error('请求失败: ' + (error.message || "网络错误"))
  } finally {
    dialogLoading.value = false
  }
}

function deleteRow(row) {
  ElMessageBox.confirm(`确定要删除会员 ${row.name} 吗？`, "删除确认", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    deleteMemberById([row.id])
  }).catch(() => {
    ElMessage.info("已取消删除")
  })
}

// 分页改变
function memberPiChange(pageNo) {
  search(pageNo, membersPi.pageSize)
}

// ======================会员的课程===========================
let courseStatusFilter = ref('') // 用于状态筛选
// 课程信息相关
let courseDlgShow = ref(false)
let courseList = ref([])
let currentMemberId = ref(null)

// 获取课程状态标签信息
function getCourseStatusLabel(status) {
  // 根据后端返回的状态值显示对应标签
  switch (status) {
    case "1":
      return {text: '已预约', type: 'primary'}
    case "2":
      return {text: '已取消', type: 'info'}
    case "3":
      return {text: '已完成', type: 'success'}
    default:
      return {text: '未知', type: 'warning'}
  }
}

// 显示会员课程信息
async function showCourse(row) {
  currentMemberId.value = row.id
  courseDlgShow.value = true
  courseStatusFilter.value = '' // 重置筛选状态
  await loadCourseData(row.id)
}
// 添加筛选函数
function filterByStatus() {
  loadCourseData(currentMemberId.value)
}

// 修改 loadCourseData 函数，支持状态筛选
async function loadCourseData(memberId) {
  try {
    // 构建请求参数
    const params = {
      memberId: memberId
    }

    // 如果有状态筛选条件，则添加到参数中
    if (courseStatusFilter.value) {
      params.status = courseStatusFilter.value
    }

    console.log("发送请求参数:", params)

    let resp = await api({
      url: "/member/courseOfMember",
      method: "get",
      params: params
    })

    console.log("加载会员课程数据:", memberId)
    console.log("会员课程数据:", resp)

    if (resp.success) {
      courseList.value = resp.data || []
    } else {
      ElMessage.error(resp.message || '获取课程信息失败')
      courseList.value = []
    }
  } catch (error) {
    console.error("请求失败详情:", error)
    ElMessage.error("获取课程信息失败: " + (error.message || "网络错误"))
    courseList.value = []
  }
}

onMounted(() => {
  search(1, membersPi.pageSize)
})
</script>

<style scoped>
.search {
  padding: 20px;
  background: white;
  border-radius: 4px;
  margin-bottom: 20px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 0;
  z-index: 100;
}

.search .el-form {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  position: sticky;
  top: 0;
  z-index: 10000;
}

.search .el-form-item {
  margin-bottom: 0;
}

.action {
  padding: 10px 20px;
  background: white;
  border-radius: 4px;
  margin-bottom: 20px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 84px;
  z-index: 99;
}

/* 为了让分页区能够正确固定，需要确保父容器允许定位 */
.grid {
  background: white;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  /* 移除 overflow: hidden 如果有的话，以免影响 sticky 定位 */
}

.el-table {
  margin-top: 10px;
}

.el-table :deep(.el-table__cell) {
  padding: 12px 0;
}

.el-table :deep(th.el-table__cell) {
  background-color: #f5f7fa;
  color: #333;
  font-weight: 500;
}

.el-dialog {
  border-radius: 8px;
}

.el-dialog :deep(.el-dialog__header) {
  border-bottom: 1px solid #e6e6e6;
  margin-right: 0;
}

.el-dialog :deep(.el-dialog__body) {
  padding: 20px;
}

.el-form-item {
  margin-bottom: 18px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  padding: 15px;
  background: white;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);

  /* 固定在底部 */
  position: sticky;
  bottom: 0;
  z-index: 10;

  /* 确保有足够的底部空间 */
  margin-bottom: 20px;
}

.el-button {
  transition: all 0.3s;
}

.el-button + .el-button {
  margin-left: 12px;
}

.el-button--primary {
  background-color: #1e3c72;
  border-color: #1e3c72;
}

.el-button--primary:hover {
  background-color: #2a5298;
  border-color: #2a5298;
}

.el-button--danger {
  background-color: #f56c6c;
  border-color: #f56c6c;
}

.el-button--danger:hover {
  background-color: #f78989;
  border-color: #f78989;
}

.el-input__inner,
.el-textarea__inner {
  border-radius: 4px;
}
</style>
